package org.swift.commons.client;

import javax.servlet.http.HttpServletRequest;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.log4j.Logger;
import org.swift.commons.util.StringUtils;

import sun.misc.BASE64Encoder;

public class RequestUtils {
	private final static Logger log = Logger.getLogger(RequestUtils.class);
	
	/**
	 * Pulls the current HttpServletRequest out of the context
	 * @return the current HttpServletRequest
	 */
	public static HttpServletRequest getRequestFromContext(){
		MessageContext ctx = (MessageContext)ContextUtil.getCurrentContext();
		if(ctx!=null){
			HttpServletRequest request = (HttpServletRequest) ctx.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
			return request;
		}else{
			log.warn("No MessageContext found! Skipping request processing...");
		}
		return null;
	}
	
	/**
	 * pulls the given header out of the request, if it exists
	 * @param headerName name of header to retrieve
	 * @return header value, if any
	 */
	public static String getRequestHeader(String headerName){
		HttpServletRequest request = getRequestFromContext();
		if(request!=null){
			String headerValue = request.getHeader(headerName);
			if(StringUtils.isNotBlank(headerValue)){
				log.debug("Found "+headerName+ " with value " + headerValue);
				return headerValue;
			}
		}
		log.debug("No header found with name "+headerName);
		return null;
	}
	
	/**
	 * Creates a base64 encoded Authorization string
	 * @param username
	 * @param password
	 * @return base64 encoded Authorization string
	 */
	public static String createBasicAuthCredentials(String username, String password){
		BASE64Encoder enc = new sun.misc.BASE64Encoder();
		String userpassword = username + ":" + password;
		String encodedAuthorization = enc.encode( userpassword.getBytes() );
		return "Basic " + encodedAuthorization;
	}
}
